package org.dinqy.integration;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.hibernate.ejb.Ejb3Configuration;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;

/**
 * @author armandino (at) gmail.com
 */
public final class EntityManagerModule extends AbstractModule {
    private static final ThreadLocal<EntityManager> entityManagerCache =
        new ThreadLocal<EntityManager>();
    
    @Provides
    @Singleton
    public EntityManagerFactory getEntityManagerFactory() {
        Ejb3Configuration ejb3Configuration = new Ejb3Configuration();
        ejb3Configuration.addResource("META-INF/persistence.xml");
        return Persistence.createEntityManagerFactory("testEntityManager");
    }

    @Provides
    public EntityManager getEntityManager(EntityManagerFactory entityManagerFactory) {
        EntityManager entityManager = entityManagerCache.get();
        if(entityManager == null) {
            entityManager = entityManagerFactory.createEntityManager();
            entityManagerCache.set(entityManager);
        }
        return entityManager;
    }

    @Override
    protected void configure() {}
    
}